package org.jsola.hr.web;

import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.TransferAccountsDetailAddDTO;
import org.jsola.hr.dto.TransferAccountsDetailUpdateDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.TransferAccountsDetailQuery;
import org.jsola.hr.query.TransferBuildDetailQuery;
import org.jsola.hr.service.ITransferAccountsDetailService;
import org.jsola.hr.vo.TransferAccountsDetailImportAllVO;
import org.jsola.hr.vo.TransferAccountsDetailListVO;
import org.jsola.hr.vo.TransferAccountsDetailVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.util.List;


/**
 * 转账明细
 *
 * @author zhr
 */
@RestController("hrTransferAccountsDetailController")
@RequestMapping(HrConstants.API_PATH + "/v1/transferAccountsDetails")
public class TransferAccountsDetailController implements ITransferAccountsDetailControllerAPI {

    @Autowired
    private ITransferAccountsDetailService transferAccountsDetailService;

    @Override
    @PostMapping
    public Result<TransferAccountsDetailVO> save(@Valid @RequestBody TransferAccountsDetailAddDTO transferAccountsDetailAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增转账明细权限校验

        return Result.success(
                transferAccountsDetailService.save(transferAccountsDetailAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody TransferAccountsDetailUpdateDTO transferAccountsDetailUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改转账明细权限校验

        int count = transferAccountsDetailService.update(transferAccountsDetailUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @PutMapping("/updateBatch")
    public Result<Integer> updateBatch(@RequestBody TransferAccountsDetailUpdateDTO transferAccountsDetailUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改转账明细权限校验

        int count = transferAccountsDetailService.updateBatch(transferAccountsDetailUpdateDTO, tokenUser);
        return Result.success(count);
    }




    @Override
    @DeleteMapping(value = "/{transferAccountsDetailId}")
    public Result<Integer> delete(@PathVariable String transferAccountsDetailId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除转账明细权限校验

        int count = transferAccountsDetailService.deleteByIds(tokenUser, transferAccountsDetailId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] transferAccountsDetailIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除转账明细权限校验

        int count = transferAccountsDetailService.deleteByIds(tokenUser, transferAccountsDetailIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{transferAccountsDetailId}")
    public Result<TransferAccountsDetailVO> findById(@PathVariable String transferAccountsDetailId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看转账明细权限校验

        return Result.success(
            transferAccountsDetailService.selectById(transferAccountsDetailId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<TransferAccountsDetailListVO>> listAll(@Valid TransferAccountsDetailQuery transferAccountsDetailQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看转账明细权限校验

        return Result.success(
            transferAccountsDetailService.select(transferAccountsDetailQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping("/selectIdsByBatchId")
    public Result<List<String>> selectIdsByBatchId(TransferAccountsDetailQuery transferAccountsDetailQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看转账明细权限校验

        return Result.success(
                transferAccountsDetailService.selectIdsByBatchId(transferAccountsDetailQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<TransferAccountsDetailListVO>> page(@Valid TransferAccountsDetailQuery transferAccountsDetailQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
            transferAccountsDetailService.selectPage(transferAccountsDetailQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping("/buildDetailAddDTOList")
    public Result<TransferAccountsDetailImportAllVO> buildDetailAddDTOList(@RequestBody TransferBuildDetailQuery transferBuildDetailQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验
        TransferAccountsDetailImportAllVO transferAccountsDetailImportAllVO =
                transferAccountsDetailService.buildDetailAddDTOList(transferBuildDetailQuery, tokenUser);
        // 入库
        transferAccountsDetailService.saveBatch(
                transferAccountsDetailImportAllVO.getSuccessTransferAccountsDetailAddDTOList(), tokenUser);
        return Result.success(
                transferAccountsDetailImportAllVO
        );
    }

    @Override
    @PostMapping("/saveBatch")
    public Result<Integer> saveBatch(@RequestBody List<TransferAccountsDetailAddDTO> transferAccountsDetailAddDTOList) {
        TokenUser tokenUser = UserContext.getUser();

        return Result.success(
                transferAccountsDetailService.saveBatch(transferAccountsDetailAddDTOList, tokenUser)
        );
    }

    @Override
    @PostMapping("/export")
    public ResponseEntity<Resource> export(@RequestBody @Valid TransferAccountsDetailQuery transferBuildDetailQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // 导出excel
        String excelFilePath = transferAccountsDetailService.selectExportList(transferBuildDetailQuery, tokenUser);
        // 编码文件名，防止乱码
        String filenames = FileKit.getNameAndEncode(excelFilePath);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    @Override
    @PostMapping("/recognitionDetailInfo")
    public Result<TransferAccountsDetailImportAllVO> recognitionDetailInfo(@RequestParam("file") MultipartFile file,
                                                                           @RequestParam("batchId")String batchId,
                                                                           @RequestParam("companyId") String companyId,
                                                                           @RequestParam("type")Integer type) {
        TokenUser tokenUser = UserContext.getUser();

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        TransferAccountsDetailImportAllVO transferAccountsDetailImportAllVO =
                transferAccountsDetailService.recognitionDetailInfo(excelFile, batchId, companyId, type, tokenUser);
        // 入库
        transferAccountsDetailService.saveBatch(
                transferAccountsDetailImportAllVO.getSuccessTransferAccountsDetailAddDTOList(), tokenUser);
        return Result.success(
                transferAccountsDetailImportAllVO
        );
    }


    @Override
    @PostMapping("/exportFailTransferAccountsDetail/{type}")
    public ResponseEntity<Resource> exportFailTransferAccountsDetail(@RequestBody List<TransferAccountsDetailAddDTO> failTransferAccountsDetailAddDTOList,
                                                                     @PathVariable Integer type) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // 导出excel
        String excelFilePath = transferAccountsDetailService
                .exportFailTransferAccountsDetail(failTransferAccountsDetailAddDTOList, type);
        // 编码文件名，防止乱码
        String filenames = FileKit.getNameAndEncode(excelFilePath);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    /**
     * 导出识别的错误信息
     *
     * @param failTransferAccountsDetailAddDTOList 导出的数据List
     * @param type 到账方式 1：支付宝 2：微信 3：银行
     * @return excel地址
     */
    @Override
    @PostMapping("/uploadFileNotLoginFailList/{type}")
    public Result<String> uploadFileNotLoginFailList(@RequestBody List<TransferAccountsDetailAddDTO> failTransferAccountsDetailAddDTOList,
                                                               @PathVariable Integer type) {

        return Result.success(
                transferAccountsDetailService.uploadFileNotLoginFailList(failTransferAccountsDetailAddDTOList, type)
        );
    }


    @Override
    @GetMapping("/selectPageByPeopleId")
    public Result<Page<TransferAccountsDetailListVO>> selectPageByPeopleId(TransferAccountsDetailQuery transferAccountsDetailQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                transferAccountsDetailService.selectPageByPeopleId(transferAccountsDetailQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping("/selectExportErrorList")
    public ResponseEntity<Resource> selectExportErrorList(TransferAccountsDetailQuery transferBuildDetailQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // 导出excel
        String excelFilePath = transferAccountsDetailService.selectExportErrorList(transferBuildDetailQuery, tokenUser);
        // 编码文件名，防止乱码
        String filenames = FileKit.getNameAndEncode(excelFilePath);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    @Override
    @PutMapping("/updateBatchAndBatchInfo")
    public Result<Integer> updateBatchAndBatchInfo(@Valid @RequestBody TransferAccountsDetailUpdateDTO transferAccountsDetailUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改转账明细权限校验

        int count = transferAccountsDetailService.updateBatchAndBatchInfo(transferAccountsDetailUpdateDTO, tokenUser);
        return Result.success(count);
    }

}

